package com.xiang.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiang.reggie.dao.SetmealMapper;
import com.xiang.reggie.dto.SetmealDto;
import com.xiang.reggie.entity.Setmeal;
import com.xiang.reggie.entity.SetmealDish;
import com.xiang.reggie.service.SetmealDishService;
import com.xiang.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 半山居雾
 * @date 2022/12/15 14:51
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐及保存菜品
     *
     * @param setmealDto setmeal dto
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //新增套餐
        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //添加套餐下的菜品到数据库
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
            setmealDishService.save(setmealDish);
        }

       /* 流处理方式处理新增菜品
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());*/
    }

    /**
     * 更新setmeal
     *
     * @param setmealDto setmeal dto
     */
    @Override
    @Transactional
    public void updateSetmeal(SetmealDto setmealDto) {
        //根据id更新setmeal套餐表数据
        this.updateById(setmealDto);

        //2、操作套餐对应的菜品数据：
        //2.1 先根据套餐id删除套餐对应的菜品数据：
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, setmealDto.getId());
        setmealDishService.remove(queryWrapper);

        //2.2 重新添加新的套餐对应的菜品数据
        Long id = setmealDto.getId();
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        if (!setmealDishes.isEmpty()) {
            for (SetmealDish setmealDish : setmealDishes) {
                setmealDish.setSetmealId(id);
            }
        }
        setmealDishService.saveBatch(setmealDishes);

    }
}
